package com.sibu.yx.promotion.admin.web.controller.common;


import com.doubo.common.model.response.CommonResponse;
import com.doubo.common.util.ExceptionUtil;
import com.doubo.common.util.FileUtil;
import com.doubo.common.util.StringUtil;
import com.sibu.yx.promotion.common.manage.ResponseManage;
import com.sibu.yx.promotion.service.biz.AliYunOssBiz;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
@RequestMapping(value = "/fileHander", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FileUploadController {

    @Autowired
    private AliYunOssBiz aliYunOssBiz;

    /**
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public CommonResponse<String> uploadFile(@RequestParam("file") MultipartFile file) {

        try {
            byte[] fileBuffer = file.getBytes();
            String fileName = file.getOriginalFilename();
            String fileExtName = FileUtil.getExtensionNotDot(fileName);
            String path = aliYunOssBiz.uploadFileByBytes(fileBuffer, fileExtName);
            if (StringUtil.isEmpty(path)) {
                return ResponseManage.fail("上传图片失败,请重试");
            }
            return ResponseManage.successIfNotNull(path);
        } catch (Exception e) {
            log.error(" file upload has a error={}", ExceptionUtil.getAsString(e));
            return ResponseManage.successIfNotNull("上传文件发生异常");
        }
    }


}
